package com.zmj.sy.mom.srv.aps.service;

import cn.hutool.core.date.DatePattern;
import com.zmj.sy.mom.srv.aps.bean.entity.base.BaseEntity;
import com.zmj.sy.mom.srv.aps.bean.entity.order.ApsOrder;
import com.zmj.sy.mom.srv.aps.bean.entity.order.ApsWorkDetail;
import com.zmj.sy.mom.srv.aps.bean.entity.order.ApsWorkOrder;
import com.zmj.sy.mom.srv.aps.bean.entity.order.Order;
import com.zmj.sy.mom.srv.aps.bean.entity.third.HexagonPush;
import com.zmj.sy.mom.srv.aps.bean.entity.third.HexagonPushPart;
import com.zmj.sy.mom.srv.aps.bean.vo.sinocam.SinoCamPushNestReqVo;
import com.zmj.sy.mom.srv.aps.config.ProjectConfig;
import com.zmj.sy.mom.srv.aps.mapper.*;
import com.zmj.sy.mom.srv.aps.utils.JsonUtils;
import com.zmj.sy.mom.srv.aps.utils.PkgUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class HexagonService {

    private final HexagonPushMapper hexagonPushMapper;

    private final HexagonPushPartMapper hexagonPushPartMapper;
    private final FactoryMapper factoryMapper;
    private final ProjectConfig projectConfig;
    private final ApsWorkDetailMapper apsWorkDetailMapper;
    private final OrderMapper orderMapper;
    private final ApsOrderMapper apsOrderMapper;
    private final ApsWorkOrderMapper apsWorkOrderMapper;

    private final RestTemplate restTemplate;

    @Transactional
    public void pushNest(SinoCamPushNestReqVo reqVo) {

        // 获取需要切割的工序
        List<String> phaseCodeList = projectConfig.getCuttingProcess();

//        LocalDate localDate = LocalDate.now().plusDays(1);

        LocalDate localDate = LocalDate.of(2024, 7, 9);


        // 获取所有需要切割的零件
        List<ApsWorkDetail> apsWorkDetailList = apsWorkDetailMapper.lambdaQuery()
                .eq(ApsWorkDetail::getOrderId, reqVo.getId())
//                .eq(ApsWorkDetail::getStatus, 2)
                .in(ApsWorkDetail::getPhaseCode, phaseCodeList)
//                .ge(ApsWorkDetail::getPlanStartDateTime, LocalDateTime.of(localDate, LocalTime.MIN))
//                .le(ApsWorkDetail::getPlanStartDateTime, LocalDateTime.of(localDate, LocalTime.MAX))
                .list();

        Order order = orderMapper.selectById(reqVo.getId());

        Map<Integer, List<ApsWorkDetail>> subOrderMap = apsWorkDetailList.stream().collect(Collectors.groupingBy(ApsWorkDetail::getApsOrderId));

        Set<Integer> apsOrderIds = subOrderMap.keySet();
        List<ApsOrder> apsOrderList = apsOrderMapper.selectBatchIds(apsOrderIds);
        Map<Integer, ApsOrder> apsOrderIdMap = apsOrderList.stream().collect(Collectors.toMap(ApsOrder::getId, Function.identity()));

        List<ApsWorkOrder> list = apsWorkOrderMapper.lambdaQuery().eq(ApsWorkOrder::getOrderId, reqVo.getId()).list();

        Map<Integer, ApsWorkOrder> workOrderMap = list.stream().collect(Collectors.toMap(BaseEntity::getId, e -> e));

        List<HexagonPush> pkgList = subOrderMap.keySet()
                .stream()
                .map(id -> {
                    ApsOrder apsOrder = apsOrderIdMap.get(id);
                    HexagonPush push = new HexagonPush();
                    push.setCustomerName(reqVo.getCustomerName());
                    push.setCustomerNo(reqVo.getCustomerNo());
                    push.setMesOrderNo(reqVo.getMesOrderNo());
                    push.setOrderEndTime(apsOrder.getPlanEndDateTime().format(DatePattern.NORM_DATETIME_FORMATTER));
                    push.setPackageName(PkgUtils.gen(apsOrder.getSeq()));

                    List<ApsWorkDetail> apsWorkDetails = subOrderMap.get(id);

                    List<HexagonPushPart> partList = apsWorkDetails.stream()
                            .map(e -> {
                                HexagonPushPart part = new HexagonPushPart();
                                ApsWorkOrder apsWorkOrder = workOrderMap.get(e.getApsWorkOrderId());
                                part.setApsId(e.getId());
                                part.setConstructNo(apsOrder.getConstructNo());
                                part.setOrderNo(apsWorkOrder.getWorkOrderCode());
                                part.setPartNo(e.getMaterNo());
                                part.setPartName(e.getMaterName());
                                part.setPartCount(e.getTotalCount().intValue());
                                part.setPlanStartDate(e.getPlanStartDateTime());
                                part.setPlanEndDate(e.getPlanEndDateTime());
                                String standard = apsWorkOrder.getStandards();
                                String[] split = standard.split("δ");
                                part.setTexture(split[0]);
                                part.setThickness(Double.parseDouble(split[1]));
                                part.setCuttingPhase(e.getPhaseCode());
                                part.setCuttingCenter(e.getGroupCode());
                                return part;
                            })
                            .collect(Collectors.toList());
                    push.setParts(partList);
                    return push;
                })
                .collect(Collectors.toList());


        Collections.sort(pkgList, Comparator.comparing(HexagonPush::getPackageName));

        pkgList.forEach(e -> {
            String jsonString = JsonUtils.toJsonString(e);
            System.out.println("请求：" + jsonString);
//            String s = restTemplate.postForObject("http://mom-srv-import-mes/mesOrderManage/apsOrderImport", e, String.class);
//            System.out.println("响应：" + s);
        });
    }

}
